<?php

namespace Cck\ArticlesSystem\Http\Controllers;

use Illuminate\Http\Request;
use Cck\ArticlesSystem\Http\Models\User;
use Cck\ArticlesSystem\Http\Resources\UserResource;
use Cck\ArticlesSystem\Http\Requests\UserStoreRequest;
use Cck\ArticlesSystem\Http\Requests\UserUpdateRequest;

class UsersController extends Controller
{
    public function index(Request $request)
    {
        $pageSize = (int)max($request->query('page_size', 15), 10);
        $page = (int)max($request->query('page', 1), 1);

        $users = User::query()
            ->when($request->query('keyword'), function ($q) use ($request) {
                $q->where('email', 'like', '%' . $request->query('keyword') . '%')
                    ->where('nickname', 'like', '%' . $request->query('keyword') . '%');
            })
            ->when($request->get('role_id'), function ($q) use ($request) {
                $q->whereHas('roles', function ($_) use ($request) {
                    $_->where('roles.id', $request->get('role_id'));
                });
            })
            ->withCount('articles')
            ->withTrashed()
            ->when($request->get('deleted') !== '', function ($q) use ($request) {
                $request->get('deleted') ? $q->whereNotNull('deleted_at') : $q->whereNull('deleted_at');
            })
            ->paginate($pageSize, ['*'], 'page', $page);

        return UserResource::collection($users);
    }

    public function show(User $user)
    {
        $user->load($this->getWith());
        return new UserResource($user);
    }

    public function store(UserStoreRequest $request)
    {
        $data = $request->validated();

        $data['password'] = \Hash::make($data['password']);

        /** @var User $user */
        $user = User::query()->create($data);

        $data['roles'] && $user->roles()->attach($data['roles']);

        return new UserResource($user);
    }

    public function edit(User $user)
    {
        return $this->view('users.edit', compact('user'));
    }

    public function update(User $user, UserUpdateRequest $request)
    {
        $data = $request->validated();

        if (isset($data['password']) && $data['password']) {
            $data['password'] = \Hash::make($data['password']);
        } else {
            unset($data['password']);
        }

        $user->update($data);

        isset($data['roles']) && $user->roles()->sync($data['roles']);

        return ['status' => true];
    }

    public function destroy(Request $request)
    {
        $ids = $request->input('ids', []);

        if (!is_array($ids)) {
            return ['status' => false, 'message' => '请传递要删除的ID数组'];
        }

        $ids = array_filter(array_unique(array_map('intval', $ids)));

        if (!count($ids)) {
            return ['status' => false, 'message' => '请传递要删除的ID数组'];
        }

        \DB::beginTransaction();

        $count = User::query()->whereIn('id', $ids)->delete();

        if (count($ids) !== $count) {
            \DB::rollBack();

            return ['status' => false, 'message' => '删除失败'];
        }

        \DB::commit();

        return ['status' => true];
    }
}
